<template>
  <div>
    <FormPanel ref="formPanel" :list="formList" :cols="3" :labelWidth="90" :formType="formType" :isSubmitBtn="false" @formChange="formChangeHandle" />
    <FilterTable
      ref="table"
      columnsRef="finance_repairFinance_receivables_payments"
      height="auto"
      :columns="columns"
      :datakey="'rows'"
      :isSelectColumn="false"
      :onCellChange="changeCells"
      :onSyncTableData="syncTableFun"
      :onColumnsChange="columns => (this.columns = columns)"
    ></FilterTable>
    <FilterTable v-show="Number(openPay) === 10041001" ref="table1" height="auto" :columns="columns1" :datakey="'rows'" :isSelectColumn="false" :onColumnsChange="columns => (this.columns1 = columns)">
      <template slot="controls">
        <el-button size="small" type="primary" @click="addHandle">新增</el-button>
      </template>
    </FilterTable>

    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'center'
      }"
    >
      <el-button type="primary" :disabled="this.isOpen === '10041002'" @click="refundOrder">电子支付退款</el-button>
      <el-button type="primary" @click="closeOrder">关单</el-button>
      <el-button type="primary" :disabled="confirmBtnLoading" :loading="confirmBtnLoading" @click="saveDialog">确 定</el-button>
      <el-button @click="closeDialog(true)">取 消</el-button>
    </div>

    <el-dialog ref="dialog" :append-to-body="true" :show-close="true" :visible.sync="showPOSCode" title="" width="40%" :before-close="closeQRCode">
      <el-input
        v-if="this.formList.find(item => item.fieldName == 'payTypeCode').initialValue === 80441009"
        v-model="formListPOS.remarkPOS"
        type="textarea"
        class="inputtextarea"
        rows="1"
        style="min-height: 80px;font-size:24px"
        readonly
      />
      <br />
      <div
        :style="{
          position: 'absolute',
          left: 0,
          bottom: 0,
          right: 0,
          zIndex: 9,
          borderTop: '1px solid #e9e9e9',
          padding: '10px 20px',
          background: '#fff',
          textAlign: 'center'
        }"
      >
        <el-button type="primary" @click="closeQRCode(true)">取 消</el-button>
      </div>
    </el-dialog>
    <BaseDialog :visible.sync="showQRCode" title="" width="900px" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <div
        :style="{
          position: 'absolute',
          left: 0,
          bottom: 0,
          right: 0,
          zIndex: 9,
          borderTop: '1px solid #e9e9e9',
          padding: '10px 20px',
          background: '#fff',
          textAlign: 'center'
        }"
      >
        <img v-if="this.formList.find(item => item.fieldName == 'payTypeCode').initialValue === 80441010" :src="setUrl" width="200px" />
        <br />
        <el-button type="primary" @click="closeQRCode(true)">取 消</el-button>
      </div>
    </BaseDialog>
    <BaseDialog :visible.sync="showQRCodeOff" title="电子支付退款" width="900px" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <QRCodeOff ref="QRCodeOff" @close="closeQRCodeOff" />
    </BaseDialog>
    <!-- wjf 2020年1月5日-->
    <BaseDialog :visible.sync="visibleCouponHandleSelect" title="会员代金券" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <coupon :vin="queryVin" :modifyType="modifyType" @onConfirm="handleCouponSelectConfirm" @close2="closeHandlerCoupon" />
    </BaseDialog>
  </div>
</template>

<script>
import moment from 'moment';
import QRcode from 'qrcode';
import { mapState } from 'vuex';
import { dictionary } from '@/utils/dictMixin';
import { addRole } from '@/api/common/auth/roleManage';
import QRCodeOff from '@/pages/finance/repairFinance/receivables/QRCodeOff';
import { getSystemDefault } from '@/api/repair/repairReception/customer/index';
import { getInvoiceType, getBalance, saveReceInfo, closeOrder, generateQRCP, generatePOS, queryPayResult, cancelPayment } from '@/api/finance/repair/receivables';
import * as types from '@/api/common/auth/roleManage/types';
import { getUserId } from '@/assets/js/auth';
import { getAllUser } from '@/api/finance/advancesReceived/register';
import { isAuthorized } from '@/utils/index';
import coupon from './coupon';
import { findAllRepair } from '@/api/repair/basicParameters';
import { getOwnerInfoByOwnerNoAndDealerCode } from '@/api/customerRepair/customerInfo/ownerVehicleManagement';
export default {
  name: 'Payments',
  components: { QRCodeOff, coupon },
  mixins: [dictionary],
  props: {
    type: {
      type: String,
      default: 'add'
    },
    rowData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    this.saveData = null;
    return {
      formListPOS: [],
      index: null,
      formList: this.createFormList(),
      columns: this.createTableColumns(),
      columns1: this.createTableColumns1(),
      formType: 'add',
      money: null,
      balance: null,
      balaPayobjId: null,
      // 定义存放结算单table
      lsita: [],
      // 定义一个定时器返回值
      timer: null,
      // 二维码退款
      showQRCodeOff: false,
      //  二维码url定义
      setUrl: '',
      tradeId: null, //
      // 二维码组件
      showQRCode: false,
      showPOSCode: false, // pos机组件
      // 是否开启支付功能
      isOpen: '10041002',
      visibleCouponHandleSelect: false,
      modifyType: true, // 该页面默认为修改
      openPay: false,
      OWNER_NO: '',
      OWNER_CODE: '',
      CUSTOMER_NAME: '',
      confirmBtnLoading: false
    };
  },
  computed: {
    ...mapState('app', ['btnLoading']),
    addBtnState() {
      return this.btnLoading[types.YAN_ROLE_ADD];
    },
    queryVin() {
      return this.lsita[0];
    }
  },

  mounted() {
    // 判断是否开启支付功能
    this.isOpend();
    this.getEmployee();
    this.getInvoiceType();
    this.formList.find(item => item.fieldName === 'receiveDate').initialValue = moment().format('YYYY-MM-DD HH:mm:ss');
    this.formList.find(item => item.fieldName === 'handler').initialValue = getUserId();
    this.getAuth();
    this.getSystemDefaultValueInfo();
  },
  methods: {
    async getOtherData() {
      let parm = {
        ownerNo: this.OWNER_NO,
        ownerCode: this.OWNER_CODE
      };
      const res = await getOwnerInfoByOwnerNoAndDealerCode(parm);
      // this.CUSTOMER_NAME = res.data
      console.log(res.data, 'getOwnerInfoByOwnerNoAndDealerCode');
      console.log(parm, 'getOwnerInfoByOwnerNoAndDealerCode');
      this.CUSTOMER_CODE = res.data.certificateNo;
      this.CUSTOMER_NAME = res.data.ownerName;
    },
    async getSystemDefaultValueInfo() {
      let resRepair = await findAllRepair();
      this.openPay = resRepair.data['9402']; // 是否启用收款
      console.log(this.openPay, 'this.openPay');
    },
    // 获取回调数据
    syncTableFun(val) {
      console.log(1);
      this.lsita = val;
      console.log('val:' + val);
    },

    // 5秒查询一次支付结果
    async queryPay(tradeId) {
      const res = await queryPayResult(tradeId);
      if (res.resultCode === 200) {
        console.log('isSuccess : ' + res.data.isSuccess);
        console.log('5秒查询一次支付结果message : ' + res.data.message);
        if (res.data.isSuccess === '1') {
          this.endClearInterval();
          this.showQRCode = false;
          this.showPOSCode = false;
          this.closeDialog(false);
          this.$notify.success({ title: '提示信息', message: res.data.message });
        }
      }
    },
    // 定时器每5秒执行一次执行5分钟
    startSetInterval(tradeId) {
      var i = 1;
      let that = this;
      this.timer = setInterval(function() {
        that.queryPay(tradeId);
        console.log('5秒执行一次:' + i);
      }, 5000);
    },
    // 关闭定时器
    endClearInterval() {
      clearInterval(this.timer);
      console.log('关闭5秒查询一次的定时器:' + this.timer);
    },
    // 定时器5分钟关闭
    startSetTime(tradeId, time) {
      var param = setTimeout(() => {
        this.endClearInterval();
        this.cancelPay(tradeId);
      }, time);
    },
    // 取消付款请求
    cancelPay(tradeId) {
      const res = cancelPayment(tradeId);
      if (res.resultCode === 200) {
        console.log('取消付款请求 : ' + res.data.isSuccess);
        console.log('取消付款请求message : ' + res.data.message);
        this.$notify.success({ title: '提示信息', message: res.data.message });
      }
      // 并且取消支付请求;
      this.showQRCode = false;
      this.showPOSCode = false;
    },
    // 关闭二维码
    closeQRCode(val) {
      this.$confirm('是否确认取消?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          // 同时关闭定时器 并发送取消请求
          this.showQRCode = false;
          this.showPOSCode = false;
          this.endClearInterval();
          this.cancelPay(this.tradeId);
        })
        .catch(() => {});
    },
    // 退款界面展示
    refundOrder() {
      let list = this.lsita;
      if (list.length === 1) {
        // 仅有一条数据则可以退款
        // 判断列表界面必须只有一条数据,
        this.showQRCodeOff = true;
        this.$nextTick(() => {
          this.$refs.QRCodeOff.openModel(list[0].BALANCE_NO);
        });
      } else {
        this.$notify.success({ title: '提示信息', message: '结算单为一条时可以退款' });
      }
    },
    // 关闭退款界面
    closeQRCodeOff(val) {
      if (!val) {
        this.closeDialog(false);
      }
      this.showQRCodeOff = false;
    },

    // 查询后台是否开启支付功能tm_default_para,8041
    async isOpend() {
      let params = { itemCode: 8041 };
      let res = await getSystemDefault(params);
      this.isOpen = res.data;
    },
    // money(rule, value, callback){
    //   if (value == 0) {
    //     callback(new Error('收款金额不能为零'));
    //   } else {
    //     callback();
    //   }
    // },
    getAuth() {
      // 是否可以修改收款日期
      if (isAuthorized('1314', '13141002')) {
        this.formList.find(item => item.fieldName === 'receiveDate').disabled = false;
      } else {
        this.formList.find(item => item.fieldName === 'receiveDate').disabled = true;
      }

      // 是否可以负收款
      if (isAuthorized('1314', '13141008')) {
        this.formList.find(item => item.fieldName === 'receiveAmount').min = -99999999;
      } else {
        this.formList.find(item => item.fieldName === 'receiveAmount').min = 0;
      }
    },
    createFormList() {
      return [
        {
          type: 'INPUT',
          label: '收费对象代码',
          fieldName: 'paymentObjectCode',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '收费对象名称',
          fieldName: 'paymentObjectName',
          disabled: true
        },
        {
          type: 'SELECT',
          itemList: [],
          label: '经手人',
          fieldName: 'handler',
          disabled: true
        },
        {
          type: 'SELECT',
          itemList: this.createDictList('8044'),
          label: '付款方式',
          fieldName: 'payTypeCode',
          rules: [{ required: true, message: '请选择付款方式', trigger: 'change' }],
          change: val => {
            this.changePayTypeCode(val);
          },
          initialValue: 80441001
        },
        {
          type: 'INPUT',
          label: '支票号码',
          fieldName: 'checkNo'
        },
        {
          type: 'DATE',
          label: '收款日期',
          dateType: 'datetime',
          fieldName: 'receiveDate',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '可用余款',
          precision: 2,
          fieldName: 'PRE_PAY',
          disabled: true
        },
        {
          type: 'INPUT_NUMBER',
          label: '本次使用余款',
          precision: 2,
          fieldName: 'usingPrePay',
          initialValue: 0,
          change: val => {
            this.changeBalance(val);
          }
        },
        {
          type: 'INPUT_NUMBER',
          label: '收款金额',
          precision: 2,
          min: 0,
          fieldName: 'receiveAmount',
          disabled: true,
          rules: [{ required: true, message: '请输入收款金额', trigger: 'change' }],
          change: val => {
            this.changeMoney(val);
          }
        },
        // {
        //   type: 'SELECT',
        //   itemList: [],
        //   label: '发票类型',
        //   fieldName: 'invoiceTypeCode'
        // },
        {
          type: 'SELECT',
          itemList: this.createDictList('1004'),
          label: '是否全部开票',
          fieldName: 'isAllInvoice',
          initialValue: 10041001
        },
        // {
        //   type: 'INPUT',
        //   label: '发票编号',
        //   fieldName: 'billNo'
        // },
        {
          type: 'INPUT',
          label: '备注',
          fieldName: 'remark',
          selfCols: 2
        },
        {
          type: 'SELECT',
          itemList: this.createDictList('1004'),
          label: '销账标志',
          fieldName: 'writeoffTag',
          initialValue: 10041002
          // },
          // wjf 2020年1月5日
          // {
          //   type: 'INPUT',
          //   label: '会员代金券',
          //   fieldName: 'coupon',
          //   readonly: true,
          //   unitRender: props => {
          //     return <el-button icon="el-icon-search" onClick={() => this.serchCouponSelect()}></el-button>;
          //   }
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '结算单号',
          dataIndex: 'BALANCE_NO',
          sorter: true
        },
        {
          title: '车牌号',
          dataIndex: 'LICENSE',
          sorter: true
        },
        {
          title: '应收账款',
          dataIndex: 'RECEIVABLE_AMOUNT',
          precision: 2,
          sorter: true
        },
        {
          title: '已收账款',
          dataIndex: 'RECEIVED_AMOUNT',
          precision: 2,
          sorter: true
        },
        {
          title: '已免账款',
          dataIndex: 'DERATED_AMOUNT',
          precision: 2,
          sorter: true
        },
        {
          title: '未收账款',
          dataIndex: 'NOT_RECEIVED_AMOUNT',
          precision: 2,
          sorter: true
        },
        {
          title: '收款金额',
          dataIndex: 'RECEIVE_AMOUNT',
          precision: 2,
          sorter: true,
          editable: false,
          defaultEditable: false,
          editRequired: true,
          editType: 'number'
        },
        {
          title: '是否结清',
          dataIndex: 'PAY_OFF',
          sorter: true,
          render: props => {
            return <span>{this.createDictText(props.row.BALANCE_CLOSE, '1004')}</span>;
          }
        },
        {
          title: '已全部开票',
          dataIndex: 'IS_ALL_INVOICE',
          sorter: true,
          render: props => {
            return <span>{this.createDictText(props.row.IS_ALL_INVOICE, '1004')}</span>;
          }
        },
        {
          title: '工单号',
          dataIndex: 'RO_NO',
          sorter: true,
          minWidth: 120
        },
        {
          title: '备件销售单号',
          dataIndex: 'SALES_PART_NO',
          sorter: true
        },
        {
          title: 'VIN',
          dataIndex: 'VIN',
          sorter: true,
          minWidth: 180
        }
      ];
    },
    createTableColumns1() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '发票类型',
          dataIndex: 'INVOICE_TYPE_CODE',
          sorter: true,
          editable: true,
          defaultEditable: true,
          // editRequired: true,
          editType: 'select',
          editItems: []
        },
        {
          title: '发票金额',
          dataIndex: 'INVOICE_AMOUNT',
          precision: 2,
          sorter: true,
          editable: true,
          defaultEditable: true,
          // editRequired: true,
          editType: 'number'
        },
        {
          title: '发票号',
          dataIndex: 'INVOICE_NO',
          sorter: true,
          editable: true,
          defaultEditable: true,
          // editRequired: true,
          editType: 'text'
        },
        {
          title: '发票日期',
          dataIndex: 'INVOICE_DATE',
          sorter: true,
          width: 150,
          editable: true,
          defaultEditable: true,
          // editRequired: true,
          editType: 'date-picker'
        },
        {
          title: '发票客户',
          dataIndex: 'CUSTOMER_CODE',
          sorter: true,
          editable: true,
          defaultEditable: true,
          // editRequired: true,
          editType: 'text'
        },
        {
          title: '备注',
          dataIndex: 'REMARK',
          sorter: true,
          width: 100,
          editable: true,
          defaultEditable: true,
          editType: 'text'
        }
      ];
    },
    // 初始化页面
    openModel(data) {
      console.log('传入', data);
      this.OWNER_NO = data[0].OWNER_NO;
      this.OWNER_CODE = data[0].OWNER_CODE;

      this.getOtherData();
      this.getBalance(data[0].PAYMENT_OBJECT_CODE);
      // for (let [key, value] of Object.entries(data[0])) {
      //   this.formList.some(item => {
      //     if (item.fieldName === key) {
      //       item.initialValue = value;
      //       return true;
      //     }
      //   });
      // }
      this.balaPayobjId = data[0].BALA_PAYOBJ_ID;
      this.formList.find(item => item.fieldName === 'paymentObjectCode').initialValue = data[0].PAYMENT_OBJECT_CODE;
      this.formList.find(item => item.fieldName === 'paymentObjectName').initialValue = data[0].PAYMENT_OBJECT_NAME;
      let sum = 0;
      for (let i = 0; i < data.length; i++) {
        // 已结清计算负的已收金额未结清结算未收账款
        data[i].RECEIVE_AMOUNT = data[i].PAY_OFF == 10041002 ? data[i].NOT_RECEIVED_AMOUNT : -data[i].RECEIVED_AMOUNT;
        sum += data[i].RECEIVE_AMOUNT;
      }
      this.money = this.formList.find(item => item.fieldName === 'receiveAmount').initialValue = sum;
      this.$refs.table.$refs.pageTable.EXECUTE_INSERT(data);
      // this.getReductionRecord(data.BALA_PAYOBJ_ID, data.OWNER_CODE )
      // this.getReceiptsDetail(data.BALANCE_NO, data.OWNER_CODE )
    },
    formChangeHandle(val) {
      this.saveData = val;
    },
    async getEmployee() {
      const res = await getAllUser();
      // console.log(res, '经手人');
      this.formList.find(item => item.fieldName === 'handler').itemList = res.data.map(x => ({ text: x.employeeName, value: x.userId + '' }));
    },
    async getInvoiceType() {
      const res = await getInvoiceType();
      // console.log(res)
      this.columns1.find(item => item.dataIndex === 'INVOICE_TYPE_CODE').editItems = res.data.map(x => ({ value: x.INVOICE_TYPE_CODE, text: x.INVOICE_TYPE_NAME }));
    },
    async getBalance(id) {
      const res = await getBalance(id);
      console.log(res);
      this.balance = this.formList.find(item => item.fieldName === 'PRE_PAY').initialValue = res.data.toFixed(2);
    },
    async saveReceInfo() {
      const res = await saveReceInfo();
      console.log(res);
    },
    // async saveDialog() {
    //   this.$refs.formPanel.SUBMIT_FORM();

    //   this.$set(this.saveData, 'dataType', '10461001')
    //   this.$set(this.saveData, 'dataSource', '10451001')
    //   if (this.saveData !== null) {
    //     const res = await addRole(this.saveData);
    //     if (res.resultCode === 200) {
    //       this.$notify.success({title: '提示信息',message:'新增成功!'});
    //       // 重新加载
    //       this.closeDialog('refresh');
    //     }else {
    //       this.$notify.error({title: '提示信息',message:res.errMsg||'新增失败!'});
    //       this.closeDialog()
    //     }
    //   }
    // },
    changeMoney(val) {
      this.money = val;
      let balance = this.formList.find(item => item.fieldName === 'usingPrePay').initialValue || 0;
      if (this.$refs.table.$refs.pageTable.dataSource.length == 1) {
        this.$refs.table.$refs.pageTable.dataSource[0].RECEIVE_AMOUNT = val + balance;
      }
    },
    changeBalance(val) {
      if (this.formList.find(item => item.fieldName === 'receiveAmount').initialValue) {
        this.formList.find(item => item.fieldName === 'receiveAmount').initialValue = this.money - val;
      }
      this.formList.find(item => item.fieldName === 'PRE_PAY').initialValue = this.balance - val;
      if (val > this.balance) {
        this.$notify.warning({ title: '提示信息', message: '本次使用余额不得大于可用余额!' });
      }
    },
    changePayTypeCode(val) {
      if (val == 80441005) {
        this.formList.find(item => item.fieldName === 'writeoffTag').initialValue = 10041002;
      } else {
        this.formList.find(item => item.fieldName === 'writeoffTag').initialValue = 10041001;
      }
      if (val === 80441010 || val === 80441009) {
        // 二维码支付,pos机
        this.formList.find(x => x.fieldName === 'usingPrePay').initialValue = 0;
        this.formList.find(x => x.fieldName === 'usingPrePay').disabled = true;
      } else {
        this.formList.find(x => x.fieldName === 'usingPrePay').disabled = false;
      }
    },
    addHandle() {
      let obj = {
        INVOICE_DATE: moment().format('YYYY-MM-DD HH:mm:ss'),
        BALA_PAYOBJ_ID: this.balaPayobjId,
        INVOICE_TYPE_CODE: 'ELEC', // ELEC - 其他 CAF1-普通发票 CAF2-增值税发票...
        CUSTOMER_CODE: this.CUSTOMER_CODE ? this.CUSTOMER_CODE : '',
        CUSTOMER_NAME: this.CUSTOMER_NAME ? this.CUSTOMER_NAME : '',
        INVOICE_AMOUNT: this.money
      };
      this.$refs.table1.$refs.pageTable.EXECUTE_INSERT(obj);
    },
    saveDialog() {
      if (this.formList.find(x => x.fieldName === 'payTypeCode').initialValue == undefined || this.formList.find(x => x.fieldName === 'payTypeCode').initialValue == '') {
        this.$notify.warning({ title: '提示信息', message: '请选择付款方式!' });
        return;
      }
      this.$refs.formPanel.SUBMIT_FORM();
      console.log('SUBMIT_FORM', this.saveData);

      let balance = this.formList.find(item => item.fieldName == 'usingPrePay').initialValue || 0;
      let flag = true;
      console.log(this.$refs.table1.$refs.pageTable.GET_REQUIRED_ERROR(), 'GET_REQUIRED_ERROR');
      if (this.saveData != null && !this.$refs.table1.$refs.pageTable.GET_REQUIRED_ERROR()) {
        if (this.saveData.usingPrePay > this.balance) {
          this.$notify.error({ title: '提示信息', message: '本次使用余额不得大于可用余额!' });
          return;
        }
        let tableData = _.cloneDeep(this.$refs.table.$refs.pageTable.dataSource);
        let sum = 0;
        for (const item of tableData) {
          sum += Number(item.RECEIVE_AMOUNT);
          if (item.RECEIVE_AMOUNT > item.NOT_RECEIVED_AMOUNT && item.NOT_RECEIVED_AMOUNT > 0) {
            flag = false;
          }
          console.log('收款', item.RECEIVE_AMOUNT, item.RECEIVED_AMOUNT);
          if (item.NOT_RECEIVED_AMOUNT > 0) {
            if (Number(item.RECEIVE_AMOUNT) + item.RECEIVED_AMOUNT < 0) {
              this.$notify.error({ title: '提示信息', message: '收款金额与已收款金额之和不能小于0!' });
              return;
            }
          }

          // else{
          //   // this.$notify.error({title: '提示信息',message:'收款金额不得大于未收款金额!'});
          //   // return
          // }
        }
        console.log(balance);
        if (sum != this.saveData.receiveAmount + balance) {
          this.$notify.error({ title: '提示信息', message: '收款金额之和不相等!' });
          return;
        }
        // 二维码支付
        let payTypeCode = this.formList.find(item => item.fieldName == 'payTypeCode').initialValue;
        if (payTypeCode === 80441010 && this.formList.find(item => item.fieldName == 'receiveAmount').initialValue <= 0) {
          this.$notify.error({ title: '提示信息', message: '收款金额必须大于0!' });
          return;
        }
        // 获取系统参数是否开启支付功能
        if (this.isOpen === '10041002' && (payTypeCode === 80441010 || payTypeCode === 80441009)) {
          this.$notify.error({ title: '提示信息', message: '未开启支付功能不可选择POS,二维码机收款' });
          return;
        }
        // console.log("flag",flag,sum,this.saveData.receiveAmount)
        if (!flag) {
          this.$notify.warning({ title: '提示信息', message: '收款金额大于未收款金额，不能收款' });
          return;
        }
        this.$confirm(flag ? '是否确认保存?' : '收款金额大于未收款金额，是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async () => {
            this.confirmBtnLoading = true;
            for (const item of tableData) {
              // if (item.NOT_RECEIVED_AMOUNT == item.RECEIVE_AMOUNT) {
              //   item.PAY_OFF = 10041001;
              // } else {
              //   item.PAY_OFF = 10041002;
              // }
              item.PAY_OFF = item.PAY_OFF == 10041001 ? 10041002 : 10041001;
            }
            let params = {
              ...this.saveData,
              paymentObjectList: tableData,
              invoiceList: this.$refs.table1.$refs.pageTable.dataSource
            };
            // 判断支付类型是否为pos,二维码,其他
            // 获取支付类型
            console.log('payTypeCode' + payTypeCode);
            try {
              if (payTypeCode === 80441010) {
                // 二维码支付
                let res = await generateQRCP(params);
                // 1）后台会返回二维码URL到前台
                // 2）前台弹出二维码收款页面并根据二维码url生成二维码页面
                // 3）执行定时器（暂定每5秒发送一次请求，暂定二维码收款页面有效时间为5分钟）
                // --获取二维码支付状态判断是否支付成功（发送二维码支付状态请求）
                // --如果支付成功：退出二维码收款页面，置灰收款页面所有选项（POS同理）
                // --如果5分钟都没有支付：发送取消收款请求去掉当前收款单号
                // 4)页面有取消按钮 如果点击取消按钮退出二维码收款页面 同时关闭定时器 并发送取消请求
                if (res.resultCode == 200) {
                  // 1字符串为二维码,2是pos机
                  let type = res.data.returnType;
                  let url = res.data.gotoUrl;
                  let tradeId = res.data.tradeId;
                  this.tradeId = tradeId;
                  const setUrl = await QRcode.toDataURL(url);
                  this.setUrl = setUrl;
                  this.showQRCode = true;
                  console.log('二维码tradeId' + tradeId);
                  // 定时器5分钟后关闭二维码界面
                  this.startSetTime(tradeId, 300000);
                  // // 定时器每5秒执行一次
                  this.startSetInterval(tradeId);
                }
              } else if (payTypeCode === 80441009) {
                let res = await generatePOS(params);
                let type = res.data.returnType;
                let tradeId = res.data.tradeId;
                this.tradeId = tradeId;
                console.log('POS机tradeId' + tradeId);
                this.formListPOS.remarkPOS = 'POS机等待支付';
                // pos机支付
                this.showPOSCode = true;
                this.startSetTime(tradeId, 600000);
                this.startSetInterval(tradeId);
              } else {
                let res = await saveReceInfo(params);
                if (res.resultCode == 200) {
                  this.$notify.success({ title: '提示信息', message: '保存成功!' });
                  this.closeDialog(false);
                }
              }
            } catch (err) {
              console.log(err, '付款失败');
            } finally {
              this.confirmBtnLoading = false;
            }
          })
          .catch(() => {});
      } else {
        this.$notify.error({ title: '提示信息', message: '有必填项未填写!' });
      }
    },

    closeOrder() {
      this.$refs.formPanel.SUBMIT_FORM();
      let obj = {};
      this.formList.find(item => {
        obj[item.fieldName] = item.initialValue || '';
      });
      // if (this.saveData != null) {
      this.$confirm('是否确认保存?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          let params = {
            // ...this.saveData,
            ...obj,
            paymentObjectList: this.$refs.table.$refs.pageTable.dataSource
          };
          // console.log("params",params)
          let res = await closeOrder(params);
          // console.log('res',res)
          if (res.resultCode == 200) {
            this.$notify.success({ title: '提示信息', message: '关单成功!' });
            this.closeDialog(false);
          }
        })
        .catch(() => {});
      // }
    },
    disable() {
      for (const item of this.columns) {
        if (item.editable == true) {
          item.disabled = true;
        }
      }
    },
    closeDialog(val) {
      this.$emit('close', val);
    },
    changeCells(keys, obj) {
      // console.log("keys",keys)
      // console.log("obj",obj)
      // console.log("table",this.$refs.table.$refs.pageTable.dataSource)
      // let key = Object.keys(keys)[0];
      // let a = key.substring(key.indexOf('|') + 1);
      // let data = this.$refs.table.$refs.pageTable.dataSource
      // if (a == 'RECEIVE_AMOUNT') {
      //   let sum = 0
      //   for (let i = 0; i < data.length; i++) {
      //     sum += parseFloat(data[i].RECEIVE_AMOUNT);
      //   }
      //   this.formList.find(item => item.fieldName === 'receiveAmount').initialValue = sum
      // }
      // console.log('changeCells',a,obj)
    },
    serchCouponSelect() {
      // console.log(this.columns.find(item => item.fieldName == 'VIN').initialValue, 'vin的值');
      this.visibleCouponHandleSelect = true;
    },
    handleCouponSelectConfirm(val) {
      let payTotalPrice = this.formList.find(item => item.fieldName == 'receiveAmount').initialValue;
      if (Math.abs(payTotalPrice) < Math.abs(val.coupon)) {
        this.$notify.error({ title: '提示信息', message: '优惠券不能大于合计金额!' });
        return false;
      } else {
        this.visibleCouponHandleSelect = false;
      }
      this.formList.find(item => item.fieldName == 'coupon').initialValue = Math.abs(val.coupon) * -1;
      this.formList.find(item => item.fieldName == 'receiveAmount').initialValue = payTotalPrice + Math.abs(val.coupon) * -1;
    },
    closeHandlerCoupon() {
      this.visibleCouponHandleSelect = false;
    }
  }
};
</script>

<style lang="less" scoped></style>
